import { CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { Button, message, Switch, Tag, Typography } from 'antd';
import dayjs from 'dayjs';
import { memo, useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';

import shareLinkSvc from '@/api/services/sharelink';
import { ShareLinkItem } from '@/common';
import Tables from '@/components/tables/tables';
import { useCopyToClipboard } from '@/hooks/event/use-copy-to-clipboard';
import useWindowWidth from '@/hooks/event/use-window-width';
import DeleteModal from '@/pages/components/modal/DeleteModal';
import UsageMethodModal from '@/pages/tiangong-ai/UsageMethodModal';
import { useDatasetStore } from '@/store/datasetStore';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { useShareLink, useShareLinkActions } from '@/store/sharelinkStore';
import { Size } from '@/types/common';
import { StorageEnum } from '@/types/enum';
import { Permission, Sharelink } from '@/types/share-link';
import { getItem } from '@/utils/storage';

import { cvpermission, removeDuplicates } from '../utils/link-utils';

const { Text } = Typography;
interface Props {
  parentSize: Size;
  className?: string;
  onEditRow?: (data: Sharelink) => void;
}

const colors: Record<number, string> = {
  1: 'volcano',
  2: 'blue',
  3: 'orange',
  4: 'red',
  5: 'purple',
  6: 'magenta',
  7: 'cyan',
  8: 'lime',
  9: 'gold',
  10: 'geekblue',
  11: 'volcano',
};

const ShareLinksTable = ({ className, parentSize, onEditRow }: Props) => {
  const { copyToClipboard } = useCopyToClipboard();
  const [deleteModal, setDeleteModal] = useState(false);
  const [currentEditRow, setCurrentEditRow] = useState<Sharelink | null>(null);
  const { loading, shareLinks, total, page, pageSize } = useShareLink();
  const { getShareLinks, setPage, setPageSize } = useShareLinkActions();
  const { allDatasets } = useDatasetStore();
  const { isPc } = useWindowWidth();
  const handlePageChange = (page: number, pageSize: number) => {
    setPage(page);
    setPageSize(pageSize);
  };

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || '';
  const { isPreview, shareId: shareIdStore } = useOrchestrationStore();
  const shareId = queryParams.get('shareId') || shareIdStore || '';

  const paginationConfig = {
    current: page,
    pageSize,
    pageSizeOptions: undefined,
    total,
    onChange: handlePageChange,
  };

  const handleDelete = async () => {
    try {
      await shareLinkSvc.deleteShareLink(currentEditRow?.id || '');
      message.success('删除分享链接成功！');
      setDeleteModal(false);
      appId && (await getShareLinks(appId));
    } catch (error) {
      console.error(error);
    }
  };

  const onDeleteClicked = (link: Sharelink) => {
    setCurrentEditRow(link);
    setDeleteModal(true);
  };

  const handleStatusChange = async (id: string) => {
    try {
      await shareLinkSvc.updateShareLinkStatus(id);
      message.success('状态更新成功');
      appId && (await getShareLinks(appId));
    } catch (e) {
      console.error(e);
    }
  };

  const [usageModalOpen, setUsageModalOpen] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<ShareLinkItem | null>(null);
  const userInfo = getItem<any>(StorageEnum.User);
  const isTianGongManager = Boolean(
    userInfo?.is_TianGong === 'true' || userInfo?.is_TianGong === true,
  );

  const handleCopyClicked = (link: Sharelink) => {
    const url = `${window.location.origin}/sharelink/${link.share_code}/${appId}/${shareId}`;
    copyToClipboard(url);
    message.success('链接已复制到剪切板！');
  };

  const handleUsageMethodClick = (record: ShareLinkItem) => {
    const url = `${window.location.origin}/sharelink/${record.share_code}/${appId}/${shareId}`;
    setSelectedRecord(url);
    setUsageModalOpen(true);
  };

  const getDatasetTags = (permissions: Permission[]) => {
    const datas = cvpermission(allDatasets, permissions);
    const uniqueDatas = removeDuplicates(datas, permissions, true);
    return uniqueDatas;
  };

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    ...(isPc
      ? [
          {
            title: '说明',
            dataIndex: 'description',
            key: 'description',
          },
        ]
      : []),
    {
      title: '到期时间',
      dataIndex: 'exp',
      key: 'exp',
      render: (exp: number) => <div>{dayjs(exp * 1000).format('YYYY-MM-DD HH:mm:ss')}</div>,
    },
    {
      title: '访客知识库',
      dataIndex: 'permissions',
      key: 'permissions',
      width: isPc ? '50%' : '10%',
      render: (_, record: Sharelink) => (
        <div
          style={{ maxWidth: isPc ? '500px' : '50px' }}
          className={`flex flex-wrap gap-1 ${isPc ? 'flex-row' : 'flex-col'}`}
        >
          {getDatasetTags(record.permissions ?? [])?.map((names, index) => {
            const name = names.join('/');
            return (
              <Tag
                style={{ maxWidth: isPc ? '500px' : '50px' }}
                color={colors[names.length]}
                className="share-link-tag truncate"
                key={index}
              >
                {name}
              </Tag>
            );
          })}
        </div>
      ),
    },
    {
      title: '启用',
      dataIndex: 'status',
      key: 'status',
      render: (_, record: Sharelink) => (
        <div>
          <Switch
            checkedChildren={<CheckOutlined />}
            unCheckedChildren={<CloseOutlined />}
            value={record.status}
            onChange={() => {
              handleStatusChange(record.id);
            }}
            disabled={isPreview}
          />
        </div>
      ),
    },
    {
      title: '',
      key: 'action',
      render: (_: any, record: ShareLinkItem) => (
        <div className="flex items-center">
          {isTianGongManager ? (
            <Button
              type="text"
              className="mr-2 text-nowrap"
              onClick={() => {
                handleUsageMethodClick(record);
              }}
            >
              使用方式
            </Button>
          ) : (
            <Button
              type="text"
              className="mr-2 text-nowrap"
              onClick={() => {
                handleCopyClicked(record);
              }}
            >
              复制链接
            </Button>
          )}
          <Button
            type="text"
            className="mr-2 text-nowrap"
            onClick={() => {
              onEditRow && onEditRow(record);
            }}
            disabled={isPreview}
          >
            编辑
          </Button>
          <Button
            type="text"
            className="text-nowrap"
            style={{ color: 'red' }}
            onClick={() => {
              onDeleteClicked(record);
            }}
            disabled={isPreview}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];

  useEffect(() => {
    appId && getShareLinks(appId);
  }, [page, pageSize, appId, getShareLinks]);

  return (
    <div className={`${className} share-link-table h-full`}>
      <Tables
        loading={loading}
        rowKey="id"
        dataSource={shareLinks}
        columns={columns}
        pagination={paginationConfig}
      />
      <DeleteModal
        open={deleteModal}
        onCancel={() => {
          setDeleteModal(false);
        }}
        onOk={() => {
          handleDelete();
        }}
      />
      <UsageMethodModal
        open={usageModalOpen}
        onCancel={() => setUsageModalOpen(false)}
        shareLink={selectedRecord}
      />
    </div>
  );
};

export default memo(ShareLinksTable);
